#!/usr/bin/env bash

set -e
set -u

export IDF_PATH=$(cd $(dirname $0); pwd)

echo "Installing ESP-IDF tools"
${IDF_PATH}/tools/idf_tools.py install

echo "Installing Python environment and packages"
${IDF_PATH}/tools/idf_tools.py install-python-env

basedir="$(dirname $0)"
echo "All done! You can now run:"
echo ""
echo "  . ${basedir}/export.sh"
echo ""

kernel="$(uname|grep -o "^[a-zA-Z0-9]\+"|tr [A-Z] [a-z])"

${IDF_PATH}/tools/idf_tools.py export --prefer-system 2>/dev/null|sed "s/;/\n/" > "env.$kernel.sh"
echo "export IDF_PATH=\"$IDF_PATH\"" >> "env.$kernel.sh"

win_env(){
  exports="$(${IDF_PATH}/tools/idf_tools.py export --prefer-system --format=key-value 2>/dev/null)"
  paths=($(echo "$exports"|grep "^PATH="|sed "s/^PATH=//"|tr ':' '\n'))
  idf_python_env_path=$(echo "$exports"|grep "^IDF_PYTHON_ENV_PATH="|sed "s/^IDF_PYTHON_ENV_PATH=//")
  paths_win=""
  for path in "${paths[@]}"; do
    if [ "$path" != '$PATH' ]; then
      path_win="$(cd "$path";pwd -W)"
      if [ -z "$paths_win" ]; then
        paths_win="$path_win"
      else
        paths_win="$paths_win;$path_win"
      fi
    fi
  done
  env_file="env.win.bat"
  echo "set \"IDF_PYTHON_ENV_PATH=$(cd "$idf_python_env_path";pwd -W)\"" > $env_file
  echo "set \"PATH=$paths_win;%PATH%\"" >> $env_file
  echo "set \"IDF_PATH=$(cd "$IDF_PATH";pwd -W)\"" >> $env_file
  sed 's/$/\r/g' -i $env_file
}

if [ "$kernel" != "linux" ]; then
  win_env
fi